package com.yiquan.search.service;

import com.yiquan.search.entity.Video;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.spark.mllib.recommendation.MatrixFactorizationModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.List;

import static com.yiquan.search.service.SparkRecommend.RECOMMEND_VIDEO_PREFIX;

/**
 * @author Tyrone
 * @date 2022/3/9 13:26
 */
@Service
@Slf4j
public class RecommendService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SparkRecommend sparkRecommend;

    public static final String TEMPORARY_USER_ID_BUCKET = "TEMPORARY_USER_ID_BUCKET";

    public static MatrixFactorizationModel recommendModel = null;

    public static final Integer RECOMMEND_NUM = 20;

    /**
     * 获取推荐视频
     *
     * @param userId
     * @return
     */
    public List<Video> getRecommendVideo(String userId) {

        if (isTemporaryUserId(userId)) {
            List<Video> hotVideo = getHotVideo();
        } else {
            List<Video> customVideo = getCustomVideo(userId);
        }
        return null;
    }

    /**
     * 判断是否临时用户
     *
     * @param userId
     * @return
     */
    public boolean isTemporaryUserId(String userId) {
        long userIdInBucket = Long.parseLong(userId);
        return redisTemplate.opsForSet().isMember(TEMPORARY_USER_ID_BUCKET, userIdInBucket);
    }

    /**
     * 获取当前最热门视频
     */
    public List<Video> getHotVideo() {
        return null;
    }

    /**
     * 个推
     */
    public List<Video> getCustomVideo(String userId) {

        List<Long> videoIdList = (List<Long>) redisTemplate.opsForValue().get(RECOMMEND_VIDEO_PREFIX + userId);
        if (videoIdList == null && videoIdList.size() <= 0) {
            List<Video> hotVideo = getHotVideo();

        }else {
            
        }
        return null;
    }

    /**
     * 每天生成模型
     */
    @Scheduled(cron = "0 0 0 * * *")
    public void getBestModel() {
        sparkRecommend.startRecommend(RECOMMEND_NUM);
    }


    public void test() {

    }
}
